import { getEchartsList } from '@/api/index';
import { getToken } from '@/utils/auth';
import { Message } from 'antd';

// action types
export const types = {
  START_FETCH: 'echartList/START_FETCH',
  SET_ERROR: 'echartList/SET_ERROR',
  RECEIVE_DATA: 'echartList/RECEIVE_DATA'
};

export const actions = {
  startFetch: () => ({ type: types.START_FETCH }),
  setError: error => ({ type: types.SET_ERROR, payload: error }),
  setEchartList: lists => ({ type: types.RECEIVE_DATA, lists }),
  fetchData: () => dispatch => {
    // start fetch
    dispatch(actions.startFetch());

    // fetch echarts data
    return getEchartsList(getToken()).then(res => {
      if (res.code === '0') {
        dispatch(actions.setEchartList(res.data));
      } else {
        dispatch(actions.setError(res.msg));
        Message.error(res.msg);
      }
    });
  }
};

const initialState = {
  isFetching: false,
  echartsList: [],
  error: null,
  isShowEcharts: true
};

// eslint-disable-next-line complexity
export default function echartsListReducer(state = initialState, action) {
  switch (action.type) {
    case types.startFetch:
      return { ...state, isFetching: true };
    case types.SET_ERROR:
      return { ...state, error: action.payload, isFetching: false, isShowEcharts: false };
    case types.RECEIVE_DATA:
      return { ...state, echartsList: action.lists, isFetching: false, isShowEcharts: false };
    default:
      return state;
  }
}

